package controllers

import (
	"crypto/md5"
	"fmt"
	beego "github.com/beego/beego/v2/server/web"
	"github.com/jinzhu/gorm"
	"huodo/models"
	"strings"
	"time"
)

type MainController struct {
	beego.Controller
}

type Res struct {
	Cre  int
	Mag  string
	Data interface{}
}

func (c *MainController) Resister() {
	//跨域
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	username := c.GetString("username")
	password := c.GetString("password")

	//密码加密封装
	md5str1 := models.Resister(password)

	_, img, ferr := c.GetFile("img")
	if ferr != nil {
		c.Data["json"] = Res{500, "文件上传失败", nil}
		c.ServeJSON(true)
		return
	}
	fmt.Println("文件大小为", img.Size/1024, "kb")
	//判断文件大小
	if img.Size/1024 > 200 {
		c.Data["json"] = Res{500, "文件大小不能大于200kb", nil}
		c.ServeJSON(true)
		return
	}
	imglast := strings.LastIndex(img.Filename, ".")
	imgindex := img.Filename[imglast+1:]
	fmt.Println("文件类型为", imgindex)
	imgtype := "png、jpg"

	if strings.Contains(imgtype, imgindex) {
		fmt.Println("文件类型符合")
	} else {
		c.Data["json"] = Res{500, "文件类型不符合", nil}
		c.ServeJSON(true)
		return
	}

	data := models.UserInfo{
		Model:    gorm.Model{},
		Username: username,
		Password: md5str1,
		Img:      img.Filename,
	}
	models.DB.Create(&data)
	c.Data["json"] = Res{200, "注册成功", data}
	c.ServeJSON(true)

}
func (c *MainController) Login() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	username := c.GetString("username")
	password := c.GetString("password")

	loginerr := models.RedisDB.Get("loginErr" + username)
	if loginerr.Val() >= "3" {
		c.Data["json"] = Res{500, "密码错误3次2小时后可再次登录", nil}
		c.ServeJSON(true)
		return
	}
	//解密
	m5 := []byte(password)
	has := md5.Sum(m5)
	md5str1 := fmt.Sprintf("%x", has) //将[]byte转成16进制

	var data models.UserInfo
	//判断是否存在
	err := models.DB.Where("username = ?", username).Where(
		"password = ?", md5str1).Find(&data).Error
	if err != nil {

		//登录失败次数
		models.RedisDB.Incr("loginErr" + username)
		//设置2小时
		models.RedisDB.Expire("loginErr"+username, time.Hour*2)

		c.Data["json"] = Res{500, "登录失败", err.Error()}
		c.ServeJSON(true)
		return
	}
	c.Data["json"] = Res{200, "登录成功", data}
	c.ServeJSON(true)

}
